<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\User;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

use Illuminate\Support\Facades\Hash;

class UserController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new User(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('name');
            $grid->column('head_img')->image('', 50, 50);
            $grid->column('email');
            $grid->column('email_verified_at');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new User(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('head_img')->image();
            $show->field('email');
            $show->field('email_verified_at');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new User(), function (Form $form) {
            $form->display('id');
            $form->text('name')->required()->maxLength(255);
            $form->image('head_img')
                ->move('/public/user/' . date('Ym'))
                ->autoUpload()
                ->removable()
                ->required()
                ->uniqueName()
                ->saveAsString();
            $form->email('email')->required()->maxLength(100);
            $form->password('password', '密码')->minLength(6)->maxLength(100);
            $form->password('password_confirm', '确认密码')->same('password')->value($form->model()->password);
            $form->datetime('email_verified_at')->required();

            $form->display('created_at');
            $form->display('updated_at');

            // 保存前回调
            $form->saving(function (Form $form) {
                $password = $form->input('password');
                // 提交的密码和原始密码值不一样，就重置密码
                if ($password !== $form->model()->password) {
                    // 密码hash加密
                    $form->password = Hash::make($password);
                } else {
                    $form->deleteInput('password');
                }

                $form->deleteInput('password_confirm');
            });
        });
    }

    protected function getValidateRule()
    {

    }

}
